<?php

/*
 * Created on 19.12.2005
 *
 */

/**
 * Sychronizer Token implementation 
 * 
 * to place the token in a form or a link 
 * <code>
 * $sync = SynchronizerToken::getInstance();
 * $sync->getHidden();
 * </code>
 * or
 * <code>
 * $sync = SynchronizerToken::getInstance();
 * $sync->getHidden();
 * </code>
 * 
 * then check in the next request with
 * <code>
 * $sync = SynchronizerToken::getInstance();
 * if (!$sync->check())
 * {
 *  print "evil user, don't do that";
 * }
 * </code>
 */
class phpinchains_SynchronizerToken
{

    /**
     * @access privat
     */
    var $token;
    /**
     * @access privat
     */
    var $newtoken;
    var $name = 'sync_token';

    /**
     * @access private
     */
    function phpinchains_SynchronizerToken($name)
    {
    	$this->name = $name;
    	$env = phpinchains_ApplicationContext::getInstance()->getEnv();
    	$this->token = $env->getSession($this->name);
        $this->newtoken = $this->generateNewToken();
        $env->setSession($this->name, $this->newtoken);
    }

    /**
     * @access private
     */
    function generateNewToken()
    {
        return uniqid(rand() * microtime(), true);
    }

    /**
     * Get the name used for synchronizer token
     */
    function getName()
    {
        return $this->name;
    }

    /**
     * static
     */
    function getInstance($name = '')
    {
    	$name = ($name?"sync_token_".$name:"sync_token");
        static $obj;
        if (empty($obj[$name]) || !is_object($obj[$name]))
        {
            $obj[$name] = new phpinchains_SynchronizerToken($name);
        }
        return $obj[$name];
    }

    function getHidden()
    {
        return '<input type="hidden" name="'.$this->getName().'" value="'.$this->newtoken.'"/>';
    }

    function getToken()
    {
        return $this->newtoken;
    }

    function check()
    {
    	$env = phpinchains_ApplicationContext::getInstance()->getEnv();
        if (!$this->token || ($GLOBALS['env']->param($this->getName()) == $this->token))
            return true;
    }

}
?>